package com.eportal.action.background;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.eportal.action.BaseAction;
import com.eportal.domain.FeeDetail;
import com.eportal.domain.FeeMain;
import com.eportal.domain.Sysopt;
import com.eportal.service.PropertyPayService;
import com.eportal.util.CityUtil;
import com.eportal.util.HomePageConfig;
import com.framework.jqgrid.JqGridPager;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 物业缴费管理
 * @author chencheng
 *
 */
public class PropertyPayAction extends BaseAction implements ModelDriven<FeeDetail> {


    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Map<String, Object> result = new HashMap<String, Object>();
    
    @Autowired
    private PropertyPayService propertyPayService;

    private Logger log = Logger.getLogger(PropertyPayAction.class);

	/**
     * 缴费管理
     */
    public String listView() {
    	String type = getRequest().getParameter("type");
    	String mpid = getMpid(type);
    	getRequest().setAttribute("type", type);
		getRequest().setAttribute("mpid", Integer.parseInt(mpid));
		getSession().setAttribute("mpid", Integer.parseInt(mpid));
		int userRole =  (Integer) getSession().getAttribute("userRole");
    	getRequest().setAttribute("userRole", userRole);
        return SUCCESS;
    }
    
    private String getMpid(String type) {
    	String[] str = null;
    	switch (type) {
		case "1":
	    	str = HomePageConfig.WUYEJIAOFEI.split(",");
			break;
		case "2":
	    	str = HomePageConfig.SHUIFEI.split(",");
			break;
		case "3":
	    	str = HomePageConfig.TINGCHEFEI.split(",");
			break;
		default:
			break;
		}
    	if(str == null){
    		return null;
    	}
    	return str[0];
	}

	/**
     * 查询统计
     */
    public void countUserPay(){
    	String type = getRequest().getParameter("type");
    	String feeMainId = getRequest().getParameter("feeMainId");
    	if (StringUtils.isBlank(type) && StringUtils.isBlank(feeMainId)) {
			return;
		}
    	Map<String, Object> map = propertyPayService.countUserPay(type,feeMainId);
    	responseBody(map);
    }
    
    /**
     * 缴费名称列表
     */
    public void list() throws Exception {
//    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
//    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	String communityId = getRequest().getParameter("communityId");
    	String type = getRequest().getParameter("type");
    	StringBuilder where = new StringBuilder("from FeeMain where type='");
    	where.append(type);
		where.append("' and communityId ='");
		where.append(communityId);
		where.append("'");
    	List<FeeMain> feeMainList = propertyPayService.list(where.toString());
        responseBody(feeMainList);
    }
    
    /**
     * 缴费项目明细管理
     */
    public String listPropertyPayView() {
    	try {
    		String sid = getRequest().getParameter("sid");
    		FeeMain feeMain = propertyPayService.getFeeMain(Long.parseLong(sid));
    		if (feeMain == null) {
    			return "error";
    		}
    		String type = getRequest().getParameter("type");
    		getRequest().setAttribute("type", type);
    		int userRole =  (Integer) getSession().getAttribute("userRole");
    		Sysopt  user= (Sysopt)getSession().getAttribute("user");
    		switch (userRole) {
    		case 1:
    		case 2:	
    		case 21:	
    			break;
    		case 3:
    		case 4:	
    			if (!user.getAgtCode().equals(feeMain.getAgtCode())) {
    				return "error";
    			}
    			break;
    		case 5:
    		case 6:	
    			if (!user.getCommunityId().equals(feeMain.getCommunityId())) {
    				return "error";
    			}
    			break;
    		default:
    			return "error";
    		}
    		String mpid = getMpid(type);
    		getRequest().setAttribute("mpid", Integer.parseInt(mpid));
    		getSession().setAttribute("mpid", Integer.parseInt(mpid));
    		getRequest().setAttribute("userRole", userRole);
    		getRequest().setAttribute("feeMainId", sid);
    		getRequest().setAttribute("communityId", feeMain.getCommunityId());
    		return SUCCESS;
		} catch (Exception e) {			
			log.error(this, e);
			return "error";
		}
    }
    
    
    /**
     * 分页查询
     */
    public void page() throws Exception {
        JqGridPager page = new JqGridPager();
        String agtCode = getRequest().getParameter("agtCode");
    	String communityId = getRequest().getParameter("communityId");
    	String areaCode = getRequest().getParameter("areaCode");
    	String itemName = getRequest().getParameter("itemName");
    	String type = getRequest().getParameter("type");
    	if (StringUtils.isBlank(type)) {
			return;
		}
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	StringBuilder where = new StringBuilder(" t.type='");
    	where.append(type);
        where.append("'");
    	if (userRole == 1 || userRole == 2 || userRole == 21) {
    		if (!StringUtils.isBlank(agtCode)) {
                where.append(" and t.agtCode = '");
                where.append(agtCode);
                where.append("'");
            }
        	if (!StringUtils.isBlank(communityId)) {
        		where.append(" and t.communityId = '");
        		where.append(communityId);
        		where.append("'");
        	}
        	if (userRole == 21) {
				where.append(" and a.sysoptId=");
				where.append(user.getSid());
			}
		}else	if (userRole == 3 || userRole == 4) {
			where.append(" and t.agtCode ='");
			where.append(user.getAgtCode());
			where.append("'");
			if (!StringUtils.isBlank(communityId)) {
        		where.append(" and t.communityId = '");
        		where.append(communityId);
        		where.append("'");
        	}
		}else if (userRole == 5 || userRole == 6) {
    		where.append(" and t.communityId ='");
    		where.append(user.getCommunityId());
    		where.append("'");
    	}
    	
    	if (StringUtils.isNotBlank(areaCode)) {
    		where.append(" and  substr(c.areaCode,1,");
        	if(CityUtil.isMunicipalities(areaCode)){//直辖市
        		where.append("2) = '");
        		where.append(areaCode.substring(0, 2));
        		where.append("'");
        	}else{									
        		where.append("4) = '");
        		where.append(areaCode.substring(0, 4));
        		where.append("'");
        	}
        }
    	if (!StringUtils.isBlank(itemName)) {
    		where.append(" and t.sid =");
    		where.append(itemName);
    	}
    	
    	page.setWhere(where.toString());
        setPage(getRequest(), page);
        List<FeeDetail> roles = propertyPayService.list(page);
        jqGridQueryMap(FeeDetail.class, getRequest(), roles, getResponse(), page);
    }
   
    /**
     * 分页查询
     */
    public void listPropertyPayPage() throws Exception {
    	JqGridPager page = new JqGridPager();
    	String feeMainId = getRequest().getParameter("feeMainId");
    	String cBuildingId = getRequest().getParameter("cBuildingId");
    	String unitId = getRequest().getParameter("unitId");
    	String roomNo = getRequest().getParameter("roomNo");
    	String roomstatus = getRequest().getParameter("roomstatus");
    	String status = getRequest().getParameter("status");
     	String ptime1 = getRequest().getParameter("ptime1");
     	String ptime2 = getRequest().getParameter("ptime2");
    	
    	if (StringUtils.isBlank(feeMainId)) {
			return;
		}
    	StringBuilder where = new StringBuilder(" fd.main_id='");
    	where.append(feeMainId);
    	where.append("'");
    	if (!StringUtils.isBlank(cBuildingId)) {
    		where.append(" and b.sid = '");
    		where.append(cBuildingId);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(unitId)) {
    		where.append(" and u.sid = '");
    		where.append(unitId);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(roomNo)) {
    		where.append(" and r.room_no like '%");
    		where.append(roomNo);
    		where.append("%'");
    	}
    	if (!StringUtils.isBlank(roomstatus)) {
    		where.append(" and r.status ='");
    		where.append(roomstatus);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(status)) {
    		where.append(" and fd.status ='");
    		where.append(status);
    		where.append("'");
    	}
    	if (!StringUtils.isBlank(ptime1)) {
   		 	where.append(" and fd.pay_time >= to_date( '");
   		 	where.append(ptime1);
   		 	where.append(" 00:00:00");
            where.append("' ,'yyyy-mm-dd HH24:mi:ss') ");
	   	}
	   	if (!StringUtils.isBlank(ptime2)) {
	   		 where.append(" and fd.pay_time <= to_date( '");
	         where.append(ptime2);
	         where.append(" 23:59:59");
		     where.append("' ,'yyyy-mm-dd HH24:mi:ss') ");
	   	}
    	
    	page.setWhere(where.toString());
    	setPage(getRequest(), page);
    	List<FeeDetail> roles = propertyPayService.listPropertyPay(page);
    	jqGridQueryMap(FeeDetail.class, getRequest(), roles, getResponse(), page);
    }
    

    /**
     * 缴费增加
     */
    public String addMenuView() {
    	String type = getRequest().getParameter("type");
    	getRequest().setAttribute("type", type);
        return SUCCESS;
    }

    /**
     * 缴费菜单新增保存
     * @throws IOException 
     */
    public void addMenu() {
    	try {
    		String itemName = getRequest().getParameter("itemName");
    		if (StringUtils.isBlank(itemName)) {
    			result.put("code", 0);
    			result.put("msg", "缴费名称必填");
    			responseBody(result);
    			return;
    		}
    		int userRole =  (Integer) getSession().getAttribute("userRole");
    		if (userRole != 5 && userRole != 6) {
    			result.put("code", 0);
    			result.put("msg", "只有社区管理员才能创建缴费菜单");
    			responseBody(result);
    			return;
    		}
    		String type = getRequest().getParameter("type");
    		if (StringUtils.isBlank(type)) {
    			result.put("code", 0);
    			result.put("msg", "无法判断缴费菜单类型，请刷新重试");
    			responseBody(result);
			}
    		result = propertyPayService.addMenuMethod(itemName,type);
		} catch (Exception e) {
			log.error(this, e);
			result.put("code", 0);
			result.put("msg", "缴费菜单新增异常");
		}
        responseBody(result);
    }
    

    /**
     * 缴费信息修改
     */
    public String editDetailView() {
    	Map<String, Object> feeDetail = propertyPayService.getFeeDetail(getModel().getSid());
        getRequest().setAttribute("feeDetail", feeDetail);
        return SUCCESS;
    }
    
    /**
     * 缴费修改
     */
    public String editMenuView() {
    	FeeMain feeMain = propertyPayService.getFeeMain(getModel().getSid());
    	getRequest().setAttribute("feeMain", feeMain);
    	return SUCCESS;
    }

    /**
     * 缴费菜单名称修改保存
     * @throws IOException 
     */
    public void updateMenu() {
    	String itemName = getRequest().getParameter("itemName");
    	String sid = getRequest().getParameter("sid");
    	if (StringUtils.isBlank(itemName)) {
    		result.put("code", 0);
			result.put("msg", "缴费名称必填");
			responseBody(result);
			return;
		}
    	result = propertyPayService.updateMenuMethod(itemName,sid);
        responseBody(result);
    }
   
    /**
     * 缴费详细修改保存
     * @throws IOException 
     */
    public void editDetail() {
    	FeeDetail feeDetail = getModel();
    	String msgStatus = getRequest().getParameter("msgStatus");
    	result = propertyPayService.updateDetailMethod(feeDetail,msgStatus);
    	responseBody(result);
    }
    

   
   

	/**
     * 缴费删除
     */
    public void delete() {
    	String param_ids = getRequest().getParameter("ids");
    	result = propertyPayService.deleteMethod(param_ids);
        responseBody(result);
    }
    

    private FeeDetail feeDetail = new FeeDetail();

    @Override
    public FeeDetail getModel() {
        return feeDetail;
    }
}
